package com.blb.netty.encode;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Random;

/**
 * Netty服务器端
 */
public class MyNettyServer {

    public void start(){
        System.out.println("启动服务器");
        //创建boss线程组，用于接收客户端
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //创建工作线程组，用于服务客户端
        NioEventLoopGroup workGroup = new NioEventLoopGroup(10);
        try {
            //创建服务器启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //配置启动对象
            serverBootstrap.group(bossGroup,workGroup)          //设置线程组
                    .option(ChannelOption.SO_BACKLOG,100) //客户端队列长度
                    .channel(NioServerSocketChannel.class)      //设置通道类型
                    .childHandler(new ChannelInitializer<SocketChannel>() { //设置通道的处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()  //设置管道
                                    .addLast(new ByteToLongDecoder()) // byte-->long
                                    .addLast(new LongToByteEncoder()) // long-->byte
                                    .addLast(new NettyServerHandler());  //自定义处理器
                        }
                    });
            //绑定端口 sync 同步化
            ChannelFuture sync = serverBootstrap.bind("192.168.114.22", 6666).sync();
            //让通道使用完后关闭
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭线程组
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    /**
     * 自定义消息处理器
     */
    static class NettyServerHandler extends SimpleChannelInboundHandler<Long>{

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Long s) throws Exception {
            System.out.println("服务器收到消息：" + s);
            //发消息给客户端
            channelHandlerContext.writeAndFlush(new Random().nextLong());
        }
    }

    public static void main(String[] args) {
        new MyNettyServer().start();
    }
}
